﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Blog.Common.Helper
{
    /// <summary>
    /// .NetCore配置文件操作类
    /// </summary>
    public class Appsettings
    {
        static IConfiguration Configuration { get; set; }
        static string contentPath { get; set; }

        /// <summary>
        /// 构造Configuration
        /// </summary>
        /// <param name="contentPath">文件路径</param>
        public Appsettings(string contentPath)
        {
            //$"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json";
            string path = "appsettings.json";
            Configuration = new ConfigurationBuilder()
                .SetBasePath(contentPath)//Microsoft.Extensions.Configuration.FileExtensions
                .Add(new JsonConfigurationSource { Path = path, Optional = false, ReloadOnChange = true })//这样的话，可以直接读目录里的json文件，而不是 bin 文件夹下的，所以不用修改复制属性
                .Build();
        }
        /// <summary>
        /// 构造Configuration
        /// </summary>
        /// <param name="configuration">Configuration</param>
        public Appsettings(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        /// <summary>
        /// 封装要操作的字符串
        /// </summary>
        /// <param name="sections">节点配置</param>
        /// <returns></returns>
        public static string app(params string[] sections)
        {
            try
            {
                if (sections.Any())
                {
                    return Configuration[string.Join(":", sections)];
                }
            }
            catch (Exception)
            {

                throw;
            }
            return string.Empty;
        }

        /// <summary>
        /// 递归获取配置信息集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sections"></param>
        /// <returns></returns>
        public static List<T> app<T>(params string[] sections)
        {
            List<T> list = new List<T>();
            Configuration.Bind(string.Join(":", sections),list);
            return list;
        }
    }
}
